package com.dietmanager.datalayer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * The Class DataLayer.
 *
 * @param <E> the element type
 */
public class DataLayer<E> {
	private final String FILE_FORMAT = ".diet";
	private String fileName;

	/**
	 * Instantiates a new data layer.
	 *
	 * @param fileName the file name
	 */
	public DataLayer(String fileName) {
		this.fileName = fileName;
	}

	/**
	 * Read object from file.
	 *
	 * @return the object
	 */
	@SuppressWarnings("unchecked")
	public E readFile() {
		E object = null;
		try {
			String fullName = String.format("%s%s", fileName, FILE_FORMAT);
			FileInputStream fileIn = new FileInputStream(fullName);
			ObjectInputStream objectIn = new ObjectInputStream(fileIn);

			object = (E) objectIn.readObject();
			objectIn.close();

		} catch (FileNotFoundException ex) {
			System.out.println("File not found");
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return object;
	}

	/**
	 * Write object to file.
	 *
	 * @param object the object
	 */
	public void writeFile(E object) {
		try {
			String fullName = String.format("%s%s", fileName, FILE_FORMAT);
			FileOutputStream fileOut = new FileOutputStream(fullName);
			ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);

			objectOut.writeObject(object);
			objectOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
